import React, { useState, useRef, useEffect } from "react";
import Select from "react-select";
import ImageCropper from "./ImageCropper";
import "./css/form.css";
import instance from "../../utils/https"; // 用于发送HTTP请求
import { useForm, Controller } from "react-hook-form";
import imageCompression from "browser-image-compression";

interface SubmissionData {
  _id: string;
  name: string; // 姓名
  position: string; // 职位
  introduce: string; // 简历（已更名为introduce）
  profileImage: string; // 头像URL
}

interface FormComponentProps {
  onSubmit: (data: SubmissionData) => void;
  time: string;
}

const FormComponent: React.FC<FormComponentProps> = ({ onSubmit, time }) => {
  const {
    register,
    handleSubmit,
    control,
    setValue,
    watch,
    formState: { errors, isValid },
    reset,
  } = useForm<SubmissionData>({
    mode: "onChange", // 每次输入变化时进行验证
    defaultValues: {
      profileImage: "",
      position: "",
      introduce: "", // 初始值设置为""
    },
  });

  const [positions, setPositions] = useState<
    { label: string; value: string }[]
  >([]);
  const [isCropping, setIsCropping] = useState<boolean>(false);
  const [imageToCrop, setImageToCrop] = useState<File | null>(null);
  const [profilePreview, setProfilePreview] = useState<string | null>(null);
  const [isImageUploaded, setIsImageUploaded] = useState<boolean>(false);

  const profileImageRef = useRef<HTMLInputElement>(null);

  // 使用useState管理isApply，并监听localStorage变化
  const [isApply, setIsApply] = useState(localStorage.getItem("isApply"));

  // 监听localStorage中isApply值的变化
  useEffect(() => {
    const handleStorageChange = () => {
      setIsApply(localStorage.getItem("isApply"));
    };

    window.addEventListener("storage", handleStorageChange);
    return () => {
      window.removeEventListener("storage", handleStorageChange);
    };
  }, []);

  // 获取职位列表
  useEffect(() => {
    const fetchPositions = async () => {
      try {
        const res = await instance.get("/getPosition", {
          params: { page: 1, pageSize: 50 }, // 请求第一页，最多50个职位
        });

        if ((res as any).code === 200) {
          const fetchedPositions = res.data.map((position: any) => ({
            label: position.jobTitle,
            value: position._id,
          }));
          setPositions(fetchedPositions); // 设置职位列表
        } else {
          console.error("获取职位失败", res.data.msg);
        }
      } catch (error) {
        console.error("获取职位时出错", error);
      }
    };

    fetchPositions(); // 调用函数获取职位
  }, []);

  // 监听profileImage变化以生成预览
  const profileImage = watch("profileImage");
  useEffect(() => {
    if (profileImage && typeof profileImage === "string") {
      setProfilePreview(profileImage);
      setIsImageUploaded(true);
    } else {
      setProfilePreview(null);
      setIsImageUploaded(false);
    }
  }, [profileImage]);

  // 处理头像上传
  const handleProfileImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setImageToCrop(e.target.files[0]);
      setIsCropping(true);
    }
  };

  // 处理裁剪完成后的图片并立即上传
  const handleCropComplete = async (croppedImage: File) => {
    try {
      const compressionOptions = {
        maxSizeMB: 1, // 最大大小1MB
        maxWidthOrHeight: 1920, // 最大宽度或高度
        useWebWorker: true,
      };

      const compressedImage = await imageCompression(
        croppedImage,
        compressionOptions
      );

      if (!compressedImage.type.startsWith("image/")) {
        throw new Error("压缩后的文件不是图片");
      }

      const formData = new FormData();
      formData.append("file", compressedImage, compressedImage.name);

      const res = await instance.post("/upload", formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });

      const imgPath = "https://zcgjcy.com/api/" + (res as any).path;

      setValue("profileImage", imgPath, { shouldValidate: true });
      setProfilePreview(imgPath);
      setIsImageUploaded(true);
      setIsCropping(false);
    } catch (error) {
      console.error("图片压缩或上传失败", error);
      alert("头像上传失败，请重试");
      setIsCropping(false);
    }
  };

  // 处理表单提交
  const onFormSubmit = async (data: SubmissionData) => {
    try {
      if (!data.profileImage) {
        alert("请上传头像");
        return;
      }

      onSubmit(data);
      reset();
      setProfilePreview(null);
    } catch (error) {
      console.error("提交失败", error);
      alert("提交失败，请重试");
    }
  };

  const customStyles = {
    control: (provided: any, state: any) => ({
      ...provided,
      backgroundColor: "white",
      color: "black",
      borderColor: state.isFocused ? "gray" : "black",
      boxShadow: "none",
      "&:hover": {
        borderColor: "gray",
      },
    }),
    menu: (provided: any) => ({
      ...provided,
      backgroundColor: "black",
      color: "white",
    }),
    option: (provided: any, state: any) => ({
      ...provided,
      backgroundColor: state.isSelected
        ? "gray"
        : state.isFocused
        ? "#444"
        : "black",
      color: "white",
    }),
    singleValue: (provided: any) => ({
      ...provided,
      color: "black",
    }),
  };

  return (
    <div className="form-container">
      {isApply === "false" ? (
        <form onSubmit={handleSubmit(onFormSubmit)} className="user-form">
          {/* 头像上传部分 */}
          <div className="form-group">
            <label>
              头像 <span className="required">*</span>:
            </label>
            {!isImageUploaded ? (
              <button
                type="button"
                onClick={() => profileImageRef.current?.click()}
                className="upload-button"
              >
                上传头像
              </button>
            ) : (
              <button
                type="button"
                onClick={() => {
                  setIsImageUploaded(false);
                  setProfilePreview(null);
                  setValue("profileImage", "", { shouldValidate: true });
                }}
                className="remove-button"
              >
                x
              </button>
            )}
            <input
              type="file"
              accept="image/*"
              style={{ display: "none" }}
              ref={profileImageRef}
              onChange={handleProfileImageUpload}
            />
            {profilePreview && !isCropping && (
              <img
                src={profilePreview}
                alt="头像预览"
                className="image-preview"
              />
            )}
            {isCropping && imageToCrop && (
              <ImageCropper
                image={imageToCrop}
                onCropComplete={handleCropComplete}
                onCancel={() => setIsCropping(false)}
              />
            )}
            {errors.profileImage && (
              <span className="error-message">
                {errors.profileImage.message}
              </span>
            )}
          </div>

          {/* 职位选择 */}
          <div className="form-group position">
            <label>
              职位 <span className="required">*</span>:
            </label>
            <Controller
              name="position"
              control={control}
              rules={{ required: "职位是必填项" }}
              render={({ field }) => (
                <Select
                  {...field}
                  options={positions}
                  placeholder="选择职位"
                  isClearable
                  className={
                    errors.position ? "select-error" : "select-default"
                  }
                  onChange={(selectedOption) => {
                    field.onChange(selectedOption ? selectedOption.value : "");
                  }}
                  value={
                    positions.find(
                      (option) => option.value === watch("position")
                    ) || null
                  }
                  styles={customStyles}
                />
              )}
            />
            {errors.position && (
              <span className="error-message">{errors.position.message}</span>
            )}
          </div>

          {/* 姓名 */}
          <div className="form-group">
            <label htmlFor="name">
              姓名 <span className="required">*</span>:
            </label>
            <input
              type="text"
              id="name"
              {...register("name", {
                required: "姓名是必填项",
                maxLength: {
                  value: 50,
                  message: "姓名不能超过50个字符",
                },
                pattern: {
                  value: /^[^\d]*$/, // 正则表达式，禁止数字
                  message: "姓名中不能包含数字",
                },
              })}
              placeholder="请输入姓名"
              className={errors.name ? "input-error" : ""}
            />
            {errors.name && (
              <span className="error-message">{errors.name.message}</span>
            )}
          </div>

          {/* introduce */}
          <div className="form-group">
            <label htmlFor="introduce">
              介绍 <span className="required">*</span>:
            </label>
            <textarea
              id="introduce"
              {...register("introduce", {
                required: "介绍是必填项", // 更新字段名称
                maxLength: {
                  value: 300,
                  message: "介绍不能超过300个字符",
                },
              })}
              placeholder="请输入自我介绍"
              rows={5}
              className={errors.introduce ? "input-error" : ""}
            />
            {errors.introduce && (
              <span className="error-message">{errors.introduce.message}</span>
            )}
          </div>

          {/* 提交按钮 */}
          <button type="submit" disabled={!isValid} className="submit-button">
            提交
          </button>
        </form>
      ) : (
        <div className="success-message">
          <button>已报名</button>
          <h3>活动结束时间：{time}</h3>
        </div>
      )}
    </div>
  );
};

export default FormComponent;
